package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"path/filepath"
	"strings"
	"xinhua_book/cache"
	"xinhua_book/models"
)

type BookController struct {
	beego.Controller
}

func (c *BookController) Add() {
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = Response{
			Code: 500,
			Msg:  "请选择要上传的图片",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	defer file.Close()
	if header.Size > 3*1024*1024 {
		c.Data["json"] = Response{
			Code: 500,
			Msg:  "上传的图片大小不可超过3MB",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	etx := map[string]bool{
		".png":  true,
		".jpg":  true,
		".jpeg": true,
	}
	suffix := strings.ToLower(filepath.Ext(header.Filename))
	if etx[suffix] == false {
		c.Data["json"] = Response{
			Code: 500,
			Msg:  "上传的图片格式只能是JPG、png、JPEG类型",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	path := "static/img/" + header.Filename
	title := c.GetString("title")
	author := c.GetString("author")
	desc := c.GetString("desc")
	if title == "" || author == "" || desc == "" {
		c.Data["json"] = Response{
			Code: 500,
			Msg:  "小说信息不可为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	var b models.Book
	b.Title = title
	b.Author = author
	b.Desc = desc
	b.Img = "http://127.0.0.1:8080/" + path
	err = b.Add()
	if err != nil {
		c.Data["json"] = Response{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	books, _ := b.GetList()
	jsonData, _ := json.Marshal(books)
	cache.Rdb.Set(cache.Ctx, "book", jsonData, 0)
	c.Data["json"] = Response{
		Code: 200,
		Msg:  "添加成功",
		Data: nil,
	}
	c.ServeJSON()
	return
}
func (c *BookController) List() {
	var books []models.Book
	cacheData := cache.Rdb.Get(cache.Ctx, "book").Val()
	if cacheData == "" {
		models.DB.Find(&books)
		jsonData, _ := json.Marshal(books)
		cache.Rdb.Set(cache.Ctx, "book", jsonData, 0)
	} else {
		json.Unmarshal([]byte(cacheData), &books)
	}
	c.Data["json"] = Response{
		Code: 200,
		Msg:  "展示成功",
		Data: books,
	}
	c.ServeJSON()
	return
}
